package com.thinkcube.edutainment.fragment;

import java.util.Iterator;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.MetaData;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.User;
import com.thinkcube.edutainment.domain.data.MobileNumber;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.domain.dto.UserDto;
import com.thinkcube.edutainment.fragment.NoticeDialogFragment.onSubmitListener;
import com.thinkcube.edutainment.service.SPreferences_;

@EFragment
public class UserFragment extends Fragment implements onSubmitListener {

	@ViewById(R.id.fname)
	EditText fname;

	@ViewById(R.id.lname)
	EditText lname;

	@ViewById(R.id.dob)
	EditText dob;

	@ViewById(R.id.nic)
	EditText nic;

	@ViewById(R.id.gender)
	EditText gender;

	@ViewById(R.id.progressBar)
	ProgressBar progress;

	@ViewById(R.id.user_profie_pic)
	ImageView userImage;

	@ViewById(R.id.teacher_title)
	TextView teacherTitle;

	@ViewById(R.id.teacher_position)
	TextView teacherDescription;

	@ViewById(R.id.teacher_username)
	TextView userName;

	@ViewById(R.id.teacher_email)
	TextView email;

	@ViewById(R.id.teacher_tele)
	TextView mobile;

	@ViewById(R.id.profile_info)
	RelativeLayout profileInfo;

	private DisplayImageOptions options;
	private ImageLoader imageLoader;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.icon)
				.showImageForEmptyUri(R.drawable.icon)
				.showImageOnFail(R.drawable.icon).cacheInMemory(true)
				.cacheOnDisc(true).displayer(new RoundedBitmapDisplayer(5))
				.build();

		imageLoader = ImageLoader.getInstance();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View myFragmentView = inflater.inflate(R.layout.userprofile, container,
				false);
		return myFragmentView;
	}

	// TODO: Rename and change types and number of parameters
	public static UserFragment newInstance() {
		UserFragment fragment = new UserFragment_();

		return fragment;
	}

	public UserFragment() {
		// Required empty public constructor
	}

	@Bean
	OAuthDto oAuthDto;

	@Background
	void gettokenUp() {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					update(userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@Trace
	@AfterViews
	@Background
	void gettoken() {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setTokenUi(userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	OAuth requestToken;

	void setTokenUi(OAuth requestTokena) {
		requestToken = requestTokena;
		doBackground(requestTokena);
	}

	@Bean
	CourseDto courseDto;
	@RestService
	UserClient userClient;

	@Pref
	SPreferences_ pref;

	@Background
	void doBackground(OAuth requestToken) {

		courseDto.setAuthToken(requestToken.getoAuth().getToken());
		courseDto.setUserId(pref.getId().get());

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					doUiUser(userClient.getUserProfileInformation(courseDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	User userProfileInformation;

	@UiThread
	void doUiUser(User user) {

		userProfileInformation = user;
		setUserDataUi();
	}

	@ViewById(R.id.profile_edit)
	Button editBtn;

	@ViewById(R.id.profile_update)
	Button updateBtn;

	@ViewById(R.id.profile_update_cancel)
	Button cancelBtn;

	@ViewById(R.id.update_panel)
	RelativeLayout uPanel;

	@ViewById(R.id.profile_sub_view)
	RelativeLayout profileSub;

	@ViewById(R.id.progressBar_2)
	ProgressBar progressSide;

	@Click(R.id.profile_update)
	void update() {
		gettokenUp();
	}

	@Bean
	UserDto userDto;

	@Background
	void update(OAuth requestToken) {

		userDto.setAuthToken(requestToken.getoAuth().getToken());
		userDto.setUserId(pref.getId().get());

		userDto.setFirstName(fname.getText().toString());

		userDto.setLastName(lname.getText().toString());
		userDto.setGender(gender.getText().toString());
		userDto.setDateOfBirth(dob.getText().toString());

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					doUiUserUp(userClient.update(userDto.getMultiValuedMap()));

					// showMessge("User updated");
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	void doUiUserUp(MetaData metaData) {
		// TODO Auto-generated method stub
		if (metaData.getStatus().equals("true")) {
			showMessge(metaData.getMessageText());
		}
	}

	@Click(R.id.profile_edit)
	void editBtnClick() {
		uPanel.setVisibility(View.VISIBLE);
		enbleEditMode();
	}

	@Click(R.id.profile_update_cancel)
	void cancelBtnClick() {
		setUserDataUi();
		disableEditMode();
		uPanel.setVisibility(View.INVISIBLE);
	}

	/* enable profile edit mode */
	void enbleEditMode() {

		for (int i = 0; i < ((ViewGroup) profileInfo).getChildCount(); ++i) {
			View nextChild = ((ViewGroup) profileInfo).getChildAt(i);
			if (nextChild instanceof EditText) {
				((EditText) nextChild).setFocusableInTouchMode(true);
			}
		}
	}

	/* disable profile edit mode */
	void disableEditMode() {
		for (int i = 0; i < ((ViewGroup) profileInfo).getChildCount(); ++i) {
			View nextChild = ((ViewGroup) profileInfo).getChildAt(i);
			if (nextChild instanceof EditText) {
				((EditText) nextChild).setFocusableInTouchMode(false);
			}
		}
	}

	/*
	 * use set the user data when initialy created and cancle the edit mode of
	 * the user profile
	 */
	void setUserDataUi() {
		progress.setVisibility(View.GONE);
		progressSide.setVisibility(View.GONE);
		profileInfo.setVisibility(View.VISIBLE);
		profileSub.setVisibility(View.VISIBLE);

		if (userProfileInformation.getUser() != null) {

			if (userProfileInformation.getUser().getPeofilePicUrl() != null) {
				imageLoader.displayImage(userProfileInformation.getUser()
						.getPeofilePicUrl(), userImage, options);
			}

			if (userProfileInformation.getUser().getFirstName() != null) {
				teacherTitle.setText(userProfileInformation.getUser()
						.getFirstName()
						+ " "
						+ userProfileInformation.getUser().getLastName());
			}
			if (userProfileInformation.getUser().getDescription() != null) {
				teacherDescription.setText(userProfileInformation.getUser()
						.getDescription());
			}
			if (userProfileInformation.getUser().getUserName() != null) {
				userName.setText(userProfileInformation.getUser().getUserName());
			}
			if (userProfileInformation.getUser().getEmail() != null) {
				email.setText(userProfileInformation.getUser().getEmail()
						.trim());
			}

			if (userProfileInformation.getUser().getMobileNumbers() != null) {

				List<MobileNumber> mobileNumersList = userProfileInformation
						.getUser().getMobileNumbers();

				Iterator<MobileNumber> it = mobileNumersList.iterator();
				while (it.hasNext()) {
					MobileNumber mobileN = it.next();
					if (mobileN.getIsPrimary()) {
						mobile.setText(mobileN.getNumber());
					}
				}

			}
			if (userProfileInformation.getUser().getFirstName() != null) {
				fname.setText(userProfileInformation.getUser().getFirstName());
			}

			if (userProfileInformation.getUser().getLastName() != null) {
				lname.setText(userProfileInformation.getUser().getLastName());
			}
			if (userProfileInformation.getUser().getNic() != null) {
				nic.setText(userProfileInformation.getUser().getNic());
			}
			if (userProfileInformation.getUser().getDateOfBirth() != null) {
				dob.setText(userProfileInformation.getUser().getDateOfBirth());
			}
			if (userProfileInformation.getUser().getGender() != null) {
				gender.setText(userProfileInformation.getUser().getGender());
			}
		} else {
			// showAlertDialog();
		}

	}

	@Override
	public void onDialogOkClick(String arg) {
		System.out.println("ON SUBMIT");

	}

	@Override
	public void onDialogCancelClick(String a) {
		System.out.println("ON CANCEL");

	}

	void showAlertDialog() {
		NoticeDialogFragment dialog = new NoticeDialogFragment();
		dialog.mListener = UserFragment.this;
		dialog.msgtext = "";
		dialog.show(getFragmentManager(), "NoticeDialogFragment");
	}
}
